import React, { Component } from 'react';
import Loading from './components/Loding'

// https://api.github.com/search/repositories?q=react&sort=stars
class App extends Component {
    state = {
        items: [],
        isLoading: true, //是否正在加载中
        isError:false //异常
    }
    /* render() {
        //1  if判断
        if (this.state.isLoading) 
            return <h3>拼命加载中....</h3>
            return (
                <div>
                    {
                        this.state.items.map(item => (
                            <p key={item.id}><a href={item.html_url}>{item.full_name}</a></p>
                            ))
                    }
                </div>
                )
        
        
    } */


    //2.三元表达式
    /*  render() {
         return this.state.isLoading ? <h3>拼命加载中....</h3> : <div>
             {
                         this.state.items.map(item => (
                             <p key={item.id}><a href={item.html_url}>{item.full_name}</a></p>
                             ))
                     }
         </div>
     } */


    // 3- 将加载中功能封装为组件
    render() {
        if(this.state.isError) return (<h3>网络连接错误，请稍后再尝试!</h3>)
        return (
            <div>
                {this.state.isLoading?<Loading/>:(
                    <div>
                        {
                            this.state.items.map(item=>(
                                <p key={item.id}>
                                    <a href={item.html_url}>{item.full_name}</a>
                                </p>
                            ))
                        }
                    </div>
                )}
            </div>
        )
    }
            
           


        //请求函数封装到外部
        async searchLoading() {
            try {
                const {items}=await this.$axios.get('/search/repositories', {
                    params: {
                        q: 'react',
                        sort:'stars'
                    }
                    })
                    this.setState({
                        items,
                        // 加载成功后取消正在加载中的状态显示
                        isLoading:false
                    })
            } catch (err) {
                this.setState({isError:true})
            }
    }
    //componentDidMount很常用,避免内部使用较多逻辑代码,封装函数到外部
    componentDidMount() {
        this.searchLoading();
    }

}

export default  App;